<template>
	<div class="app-container">
		<el-form
			:model="queryParams"
			ref="queryRef"
			:inline="true"
			v-show="showSearch"
			label-width="68px"
		>
			<el-form-item label="文章标题" prop="articleTitle">
				<el-input
					v-model="queryParams.articleTitle"
					placeholder="请输入文章标题"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="是否启用" prop="status">
				<el-select
					v-model="queryParams.status"
					placeholder="请选择是否启用"
					clearable
				>
					<el-option
						v-for="dict in if_exit"
						:key="dict.value"
						:label="dict.label"
						:value="dict.value"
					/>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery"
					>搜索</el-button
				>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					plain
					icon="Plus"
					@click="handleAdd"
					v-hasPermi="['article:message:add']"
					>新增</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="success"
					plain
					icon="Edit"
					:disabled="multiple"
					@click="open = true"
					v-hasPermi="['article:message:edit']"
					>批量修改</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="danger"
					plain
					icon="Delete"
					:disabled="multiple"
					@click="handleBatchDelete"
					v-hasPermi="['article:message:remove']"
					>批量删除</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="Download"
					@click="handleExport"
					v-hasPermi="['article:message:export']"
					>导出</el-button
				>
			</el-col>
			<right-toolbar
				v-model:showSearch="showSearch"
				@queryTable="getList"
			></right-toolbar>
		</el-row>

		<el-table
			v-loading="loading"
			:data="messageList"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="文章id" align="center" prop="uid" width="200">
				<template #default="{ row }">
					<div style="display: flex; justify-content: center">
						<el-button
							type="primary"
							@click="copy(row.uid)"
							size="small"
							style="margin-left: 10px"
							>复制链接</el-button
						>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="文章标题" align="center" prop="articleTitle" />
			<el-table-column label="发布人" align="center" prop="userName" />
			<el-table-column label="排序" align="center" prop="sort" />
			<el-table-column
				label="封面/分享图标"
				align="center"
				prop="titleUrl"
				width="140"
			>
				<template #default="scope">
					<image-preview :src="scope.row.titleUrl" :width="50" :height="50" />
				</template>
			</el-table-column>
			<el-table-column
				label="是否启用"
				align="center"
				prop="status"
				width="200"
			>
				<template #default="scope">
					<!-- <dict-tag :options="if_exit" :value="scope.row.status" /> -->
					<el-switch
						:value="ifExitFun(scope.row.status)"
						@change="changeExit(scope.row)"
						size="large"
						active-text="启用"
						inactive-text="停用"
					/>
				</template>
			</el-table-column>
			<el-table-column label="访问量" align="center" prop="seeNum">
				<template #default="scope">
					{{ scope.row.seeNum ? scope.row.seeNum : 0 }}
				</template>
			</el-table-column>
			<el-table-column label="创建时间" align="center" prop="createTime" />
			<el-table-column
				label="操作"
				align="center"
				class-name="small-padding fixed-width"
			>
				<template #default="scope">
					<el-button
						link
						type="primary"
						icon="Edit"
						@click="handleUpdate(scope.row)"
						v-hasPermi="['article:message:edit']"
						>修改</el-button
					>
					<el-button
						link
						type="primary"
						icon="Delete"
						@click="handleDelete(scope.row)"
						v-hasPermi="['article:message:remove']"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 添加或修改文章管理对话框 -->
		<el-dialog :title="title" v-model="open" width="700px" append-to-body>
			<el-form
				ref="messageRef"
				:model="form"
				:rules="rules"
				label-width="120px"
			>
				<el-form-item label="返回跳转链接" prop="returnUrl">
					<el-input v-model="form.returnUrl" placeholder="请输入返回跳转链接" />
				</el-form-item>
				<el-form-item label="直跳" prop="goUrl">
					<el-input v-model="form.goUrl" placeholder="请输入直跳" />
				</el-form-item>
				<el-form-item label="顶部广告链接" prop="topUrl">
					<el-input v-model="form.topUrl" placeholder="请输入顶部广告链接" />
				</el-form-item>
				<el-form-item label="底部广告链接" prop="bottomUrl">
					<el-input v-model="form.bottomUrl" placeholder="请输入底部广告链接" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="Message">
import {
	listMessage,
	getMessage,
	delMessage,
	addMessage,
	updateMessage,
	updateMessageList,
} from '@/api/article/message';

import { onMounted, watch } from 'vue';
import useClipboard from 'vue-clipboard3';
import useUserStore from '@/store/modules/user';

const user = useUserStore();
const { toClipboard } = useClipboard();
const { proxy } = getCurrentInstance();
const { if_exit } = proxy.useDict('if_exit');

const messageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

const route = useRoute();
const router = useRouter();

const data = reactive({
	form: {},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		articleTitle: null,
		status: null,
	},
	rules: {
		articleTitle: [
			{ required: true, message: '文章标题不能为空', trigger: 'blur' },
		],
	},
});

const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
	console.log(user.id);
	console.log(user.roles);
	getList();
});

watch(
	() => route.path,
	() => {
		// 当路由发生变化时执行的逻辑
		getList();
	}
);

// 是否启用
function ifExitFun(e) {
	return e === '1' ? true : false;
}

// 切换启用按钮
function changeExit(row) {
	updateMessage({
		uid: row.uid,
		status: 1 - row.status + '',
	}).then((response) => {
		proxy.$modal.msgSuccess('修改成功');
		getList();
	});
}

/** 查询文章管理列表 */
function getList() {
	loading.value = true;
	let userId = null;
	if (
		user.roles.find((res) => res == 'admin') ||
		user.roles.find((res) => res == 'jizouyun')
	) {
		userId = null;
	} else {
		userId = user.id;
	}
	listMessage({
		...queryParams.value,
		user: userId,
	}).then((response) => {
		messageList.value = response.rows;
		total.value = response.total;
		loading.value = false;
	});
}

async function copy(e) {
	await toClipboard(`?uid=${e}`);
	proxy.$modal.msgSuccess('复制成功');
}

// 取消按钮
function cancel() {
	open.value = false;
	reset();
}

// 表单重置
function reset() {
	form.value = {
		uid: null,
		articleTitle: null,
		sort: null,
		user: null,
		titleUrl: null,
		returnUrl: null,
		backedMusic: null,
		goUrl: null,
		topImg: null,
		topUrl: null,
		bottomImg: null,
		bottomUrl: null,
		status: null,
		seeNum: null,
		richText: null,
		createTime: null,
		updateTime: null,
	};
	proxy.resetForm('messageRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm('queryRef');
	handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
	ids.value = selection.map((item) => item.uid);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
	router.push('/article/addMessage');
}

/** 修改按钮操作 */
function handleUpdate(row) {
	const _uid = row.uid || ids.value;
	router.push(`/article/addMessage?uid=${_uid}`);
}

/** 提交按钮 */
function submitForm() {
	const data = ids.value.map((res) => {
		return {
			uid: res,
			returnUrl: form.value.returnUrl,
			goUrl: form.value.goUrl,
			topUrl: form.value.topUrl,
			bottomUrl: form.value.bottomUrl,
		};
	});
	console.log(data);
	updateMessageList(data).then(() => {
		proxy.$modal.msgSuccess('修改成功');
		open.value = false;
		getList();
		reset();
	});
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _uids = row.articleTitle
  proxy.$modal
    .confirm('是否确认删除文章管理编号为"' + _uids + '"的数据项？')
    .then(function () {
      return delMessage(row.uid)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
    .catch(() => {})
}

// 批量删除
function handleBatchDelete() {
	proxy.$modal
		.confirm('是否确认删除已选中的文章？')
		.then(function () {
			return delMessage(ids.value)
		})
		.then(() => {
			getList()
			proxy.$modal.msgSuccess("删除成功")
		})
		.catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download(
		'article/message/export',
		{
			...queryParams.value,
		},
		`message_${new Date().getTime()}.xlsx`
	);
}
</script>
